import json

from QQLoginTool.QQtool import OAuthQQ
from django import http
from django.conf import settings
from django.contrib.auth import login
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from apps.oauth import models
from apps.oauth.models import QQUser, Weibo
from apps.users.models import User
from apps.users.utils import jiajiemi
from ..users import utils
#跳转qq登陆界面
class QQLoginView(View):
    def get(self,request):
        #创建登陆qq的操作对象
        qq_cli = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        login_url = qq_cli.get_qq_url()
        return redirect(login_url)
        # return HttpResponse('1')

 #QQ登陆成功携带着code跳转到此处

#QQ登陆成功回调返回code
class QQReturnView(View):
    def get(self,request):
        #获取code
        code = request.GET.get('code')
        #判断code是否存在，不存在返回
        if not code:
            return http.HttpResponseForbidden('code不存在')
        #存在说明回调登陆成功
        #通过code获取token 和 openid,需要认证工具对象
        qq_cli = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        try:
            token = qq_cli.get_access_token(code)
            openid = qq_cli.get_open_id(token)
            print(openid)
        except Exception as e:
            return http.HttpResponseForbidden('认证失败')
        #判断openid 是否绑定了用户即判断openid是否存在于qq的表中
        try:
            qq_user = models.QQUser.objects.get(openid=openid)#不存在会报错
        except Exception:
            #不存在就跳转到绑定页面 ,传给网页openid用于注册后写入表中
            #细节优化,将openid加密发送

            scret_openid = jiajiemi().jiami(openid)
            return render(request,'oauth_callback.html',{'openid':scret_openid})
        #存在则保持登陆状态session,和保留登陆信息cookie
        # login中封装了session
        login(request,qq_user.user) #绑定了也会有user值,因为绑定同时要写入两张表
        qq_user=qq_user.user #从查询出来的对象里面获得user对下
        response = redirect(reverse('index'))
        response.set_cookie('username',qq_user.username,max_age=3600*24*14)
        return response

        # 如果没绑定会跳转到绑定界面根据表单POST提交到相同的界面
    #来这的都是没有绑定过openid的, 但是要判断是否已经注册了会员
    def post(self, request):
        mobile = request.POST.get('mobile')
        openid = request.POST.get('openid')

        #解密
        openid = jiajiemi().jiemi(openid)
        password = request.POST.get('pwd')
        #判断手机号是不是注册过
        try:
            user = User.objects.get(mobile=mobile)
            print(user)
        except Exception as e:
            #没有注册过,进行注册
            user = User.objects.create_user(username=mobile,mobile=mobile,password=password)
            # return HttpResponse('注册成功')



        #如果用户存在 校验密码
        else:
            if not user.check_password(password):
                print('密码错误')
                return render(request,'oauth_callback.html',{'errsmg':'密码错误'})

        print('excpet之后我还可以继续执行')
        #密码正确,将已注册过的用户绑定上openidQQ表,下次可以直接用qq登录判断openid存在即可登录
        try:
            models.QQUser.objects.create(openid=openid,user=user)
        except Exception as e:
            #存在用户,但是绑定失败

            return render(request, 'oauth_callback.html', {'errsmg': 'QQ登录失败'})






        #绑定成功后保存登录状态
        login(request,user)
        next=request.GET.get('next')
        response = redirect(reverse('index'))
        response.set_cookie('user.username',user.username,max_age=3600 * 24 * 15)
        return response

#绑定用户  等qq平台通过后就不用这个接口了
# class QQBindView(View):
#     def get(self,request):
#
# return render(request,'oauth_callback.html',{'a':11})



from . import sinaweibopy3
#跳转微博登陆界面
class WeiboLoginView(View):

    def get(self,request):
        # APP_KEY = 3305669385
        # APP_SECRET = '74c7bea69d5fc64f5c3b80c802325276'
        # REDIRECT_URL = 'http://www.meiduo.site:8000/sina_callback'
        #创建微博对象

        client = sinaweibopy3.APIClient(app_key=settings.APP_KEY,app_secret=settings.APP_SECRET,redirect_uri=settings.REDIRECT_URL)
        url = client.get_authorize_url()

        return redirect(url)

#微博回调地址
class WeiboReturnView(View):

    def get(self,request):
        #获取code
        code = request.GET.get('code')
        #创建实例对象
        client = sinaweibopy3.APIClient(app_key=settings.APP_KEY,app_secret=settings.APP_SECRET,redirect_uri=settings.REDIRECT_URL)
        result = client.request_access_token(code)
        token = result.access_token
        depires_in = result.expires_in
        uid = result.uid
        #如果没有uid 那就去绑定去吧
        try:
            user = Weibo.objects.get(uid=uid)
        except Exception:
            #这边跳转, 会表单post传回这个路由
            return render(request,'sina_callback.html',{'uid':uid})
        #那如果有 就用表中的user登陆,保持会话记录

        login(request,user.user)
        response = redirect(reverse('index'))
        response.set_cookie('username', user.user.username, max_age=3600 * 24 * 14)
        return response

    #表单保存发送axios到这
    def post(self,request):
        json_dict = json.loads(request.body.decode())
        password =json_dict.get('password')
        mobile =json_dict.get('mobile')
        uid =json_dict.get('uid')
        #校验参数

        #判断该手机号是否已经注册,如果注册了,判断密码是否正确后直接登陆
        try:
            user = User.objects.get(mobile=mobile)
        except Exception:
            #如果不存在则注册写入
            print('执行excpeting,在微博回调')
            user = User.objects.create_user(username=mobile,password=password,mobile=mobile)
        print('except之后还能继续执行代码')
        #如果存在校验密码
        if not user.check_password(password):
            return render(request, 'sina_callback.html', {'errsmg': '密码错误'})

        #如果密码正确,写入微博表中
        Weibo.objects.create(user=user,uid=uid)
        login(request,user)
        #在前端已经重定向了
        response = redirect(reverse('index'))
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response





#微博绑定地址测试,用微博后就不用这个地址了
# class WeiboBindView(View):
#     def get(self,request):
#         return render(request,'sina_callback.html')




